import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

// 前端路由守卫：验证token有效性
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('auth_token')
  
  // 允许访问登录和注册页面
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }
  
  // 没有token，跳转到登录页
  if (!token) {
    next('/login')
    return
  }
  
  // 验证token有效性
  try {
    const res = await fetch('/api/users/profile', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.ok) {
      const data = await res.json()
      if (data.code === 0) {
        // token有效，更新用户信息
        localStorage.setItem('auth_user', JSON.stringify(data.data))
        next()
      } else {
        // token无效，清除并跳转登录
        localStorage.removeItem('auth_token')
        localStorage.removeItem('auth_user')
        next('/login')
      }
    } else {
      // 请求失败，清除并跳转登录
      localStorage.removeItem('auth_token')
      localStorage.removeItem('auth_user')
      next('/login')
    }
  } catch (e) {
    console.error('验证token失败', e)
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
    next('/login')
  }
})

createApp(App).use(router).mount('#app')
